<template>
  <div class="file-explorer">
    <Flex justify="space-between" align="center">
      <Space> 
        <input
        type="file"
        webkitdirectory
        directory
        multiple
        @change="handleFolderSelect"
        style="display: none"
        ref="fileInputRef"
        />
        <Button type="primary" @click="handleButtonClick">
        选择文件夹
        </Button>
        <Divider type="vertical" />
        <Button @click="remove()">删除</Button>
        <Button danger @click="remove(true)">清空</Button>
    </Space>
    <Space>
      <span>导出文件名称：</span>
      <Input v-model:value="exportFileName" placeholder="请输入导出名称"/>
      <Button type="primary" @click="exportExcel">导出Excel</Button>
    </Space>
    </Flex>
    <Table :dataSource="fileList" 
    row-key="id"
    style="margin-top: 16px" 
    :pagination="{size:'default', showTotal: (total) => `共 ${total} 行`, 
      defaultPageSize: 20,
      showSizeChanger: true, pageSizeOptions: ['20', '30', '50', '100']}"
    size="middle" 
    :loading="loading"
    :row-selection="{ selectedRowKeys:selectRowKeys, onChange: onSelectChange  }">
      <Table.Column title="日期" dataIndex="created"  key="created" :width="100"></Table.Column>
      <Table.Column title="制作内容" dataIndex="name" key="name"/>
      <Table.Column title="扩展名" dataIndex="exif" key="exif"/>
      <Table.Column title="材质" dataIndex="material" key="material" :width="120">
        <template #default="{ record }">
          {{ record.material || '' }}
        </template>
      </Table.Column>
      <Table.Column title="宽" dataIndex="width" key="width" :width="100">
        <template #default="{ record }">
          {{ record.width?.toFixed(2) }}
        </template>
      </Table.Column>
      <Table.Column title="高" dataIndex="height" key="height" :width="100">
        <template #default="{ record }">
          {{ record.height?.toFixed(2) }}
        </template>
      </Table.Column>
      <Table.Column title="数量" dataIndex="quantity" key="quantity"  :width="100"/>
      <Table.Column title="面积" dataIndex="area" key="area" :width="100">
        <template #default="{ record }">
          {{ record.area?.toFixed(2) }}
        </template>
      </Table.Column>
      <Table.Column title="单位" dataIndex="unit" key="unit" :width="100"/>
    </Table>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { Table, Button,Space ,Input,Flex,Modal,Divider} from 'ant-design-vue'
import * as XLSX from 'xlsx'

const fileInputRef = ref<HTMLInputElement | null>(null)
type Key = number | string
interface FileInfo {
  id:number
  name: string
  path: string
  created: string
  width?: number
  height?: number
  area?: number
  unit?: 'cm' | 'm' | 'px' | '平方米',
  exif?: string;
  dimensionSource?: 'filename' | 'image'
  quantity: number; // 添加数量属性
  thumbnail?: string,
  material?: string,
    price?: number|undefined,
    amount?: number|undefined,
    remark?: string,
}
const exportFileName = ref()
const fileList = ref<FileInfo[]>([])
const loading = ref(false)
const selectRowKeys = ref<Key[]>([])

//尝试从本地缓存中读取fileList
fileList.value = JSON.parse(localStorage.getItem('fileList') || '[]')

//设置导出名称为 当前时间 格式化为YYYY-MM-DD HH:mm:ss
exportFileName.value = '广告物料清单-'+ formatDate(Date.now());
const handleFolderSelect = async (event: Event) => {
  try{
    loading.value = true
    const input = event.target as HTMLInputElement;
    if (input.files?.length) {
      const files = Array.from(input.files).filter(f => f.name !== 'Thumbs.db');
      const fileInfoPromises = files.map(async (file) => {
        const info: FileInfo = {
          id:file.lastModified,
          name:file.name.replace(/\.[^/.]+$/, ""),
          exif: getFileExtension(file.name),
          path: (file as any).webkitRelativePath,
          created: formatDate(file.lastModified),
          quantity: 1 // 默认为1
        };
        // 先尝试从文件名解析尺寸
        const sizeMatch = file.name.match(/(\d+\.?\d*)(mm|cm)?[x×](\d+\.?\d*)(mm|cm)?/i);
        const quantityMatch = file.name.match(/=(\d+)张|块|套/i); // 识别数量
        if (quantityMatch) {
          info.quantity = parseInt(quantityMatch[1]);
        }
        if (sizeMatch) {
          const width = parseFloat(sizeMatch[1]);
          const height = parseFloat(sizeMatch[3]);
          const unit = sizeMatch[2] || sizeMatch[4] || 'px';
          const conversionRate = unit === 'cm' ? 0.01 : unit === 'mm' ? 0.001 : 1;
          info.width = width * conversionRate;
          info.height = height * conversionRate;
          info.unit = '平方米';
          info.area = info.width * info.height * info.quantity; // 修改面积计算逻辑
          info.dimensionSource = 'filename';
        } else if (file.type.startsWith('image/')) {
          const img = new Image();
          img.src = URL.createObjectURL(file);
          img.onerror = () => {
            console.error(`图片加载失败: ${file.name}`);
          };
          await new Promise((resolve, reject) => {
            img.onload = resolve;
            img.onerror = reject;
          });
          info.width = img.width;
          info.height = img.height;
          info.unit = undefined;
          info.area = undefined; // 修改面积计算逻辑
          info.dimensionSource = 'image';
        } else {
          // 文件名中不存在尺寸信息，不计算宽高和面积
          info.width = undefined;
          info.height = undefined;
          info.area = undefined;
          info.unit = undefined;
          info.dimensionSource = undefined;
        }
        return info;
      });
      fileList.value = await Promise.all(fileInfoPromises);
      //根据info.created 进行排序
      fileList.value.sort((a, b) => {
        const dateA = new Date(a.created);
        const dateB = new Date(b.created);
        return dateA.getTime() - dateB.getTime();
      });

      //写入本地缓存
      localStorage.setItem('fileList', JSON.stringify(fileList.value));
    }
  }finally {
    loading.value = false
  }
}
function formatDate(timestamp: number): string {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
function getFileExtension(filename: string): string {
  const parts = filename.split('.');
  return parts.length > 1 ? parts[parts.length - 1] : '';
}
const exportExcel = () => {
  const ws = XLSX.utils.json_to_sheet(fileList.value.map(f => ({
    '日期': f.created,
    '制作内容': f.name,
    '材质': f.material || '',
    '宽': f.width?.toFixed(2),
    '高': f.height?.toFixed(2),
    '数量': f.quantity,
    '面积': f.area?.toFixed(2),
    '单位': f.unit,
    '单价': f.price || '',
    '金额': f.amount || '',
    '备注': f.remark || ''
  })));
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Files');
  XLSX.writeFile(wb, `${exportFileName.value}.xlsx`);
}

const handleButtonClick = () => {
  if (fileInputRef.value) {
    fileInputRef.value.click()
  } else {
    console.error('文件输入框引用未找到')
  }
}
const onSelectChange = (selectedRowKeys: Key[]) => {
  selectRowKeys.value = selectedRowKeys;
}
const remove = (all?:boolean) => {
  if(selectRowKeys.value.length || !all){
    fileList.value = fileList.value.filter(f => !selectRowKeys.value.includes(f.id))
    localStorage.setItem('fileList', JSON.stringify(fileList.value))
  }else {
    Modal.confirm({
      title: '确定要清空文件列表么？',
      content: '删除后无法恢复',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        fileList.value = []
        localStorage.removeItem('fileList')
      },
    });
  }
}
</script>

<style scoped>

</style>